package com.thinkit.security.config;
import com.thinkit.security.custom.CustomUserAuthenticationProvider;
import com.thinkit.utils.properties.PermitAllUrlProperties;
import com.thinkit.utils.utils.Checker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import java.util.List;

@Configuration
@EnableWebSecurity
public class GloableSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	PermitAllUrlProperties permitAllUrlProperties;


	@Autowired
	CustomUserAuthenticationProvider customUserAuthenticationProvider;


	@Value("${spring.application.name}")
	private String application;


    @Override
	public void configure(WebSecurity web) throws Exception {
		List<String> ignores =permitAllUrlProperties.ignores(application);
        if(Checker.BeNotEmpty(ignores)){
			web.ignoring().antMatchers(ignores.toArray(new String[ignores.size()]));
		}
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		List<String> ignores =permitAllUrlProperties.ignores();
		http
		.requestMatchers().anyRequest()
		.and()
		.authorizeRequests()
		.antMatchers(ignores.toArray(new String[ignores.size()])).permitAll();
	}


	@Bean
	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return authenticationManager();
	}

	/**
	 * Spring Security认证服务中的相关实现重新定义
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// 加入自定义的安全认证
		auth.authenticationProvider(customUserAuthenticationProvider);
	}
}
